import { Injectable } from '@nestjs/common';
import { CreateSysDictDto } from './dto/create-sys-dict.dto';
import { UpdateSysDictDto } from './dto/update-sys-dict.dto';
import { Dict } from '@/modules/system/dict/entities/dict.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Not, Repository } from 'typeorm';
import { ResultData } from '@/common/utils/result';
import { instanceToPlain } from 'class-transformer';
import { FindListSysDictDto } from '@/modules/system/dict/dto/find-list-sys-dict.dto';

@Injectable()
export class DictService {
    constructor(
        @InjectRepository(Dict)
        private readonly dictRepo: Repository<Dict>,
    ) {
    }
    
    async create(createSysDictDto: CreateSysDictDto) {
        return ResultData.ok(await this.dictRepo.save(createSysDictDto));
    }
    
    async findAll(findAllDto: FindListSysDictDto) {
        const { page, size, parentId, code, name } = findAllDto;
        const take = size || 15;
        const skip = ((page || 1) - 1) * take;
        const where = {
            ...(parentId ? { parentId } : null),
            ...(code ? { code } : null),
            ...(name ? { name: Like(`%${name}%`) } : null),
        };
        return ResultData.rowOk(instanceToPlain(await this.dictRepo.findAndCount({
            order: {
                id: 'DESC',
            },
            where,
            skip,
            take,
        })));
    }
    
    async findDictByCode({ code }) {
        return ResultData.ok(instanceToPlain(await this.dictRepo.find({
            where: {
                code,
                parentId: Not(-1),
            },
            select: ['dictKey', 'dictValue', 'id'],
        })));
    }
    
    findOne(id: number) {
        return `This action returns a #${id} sysDict`;
    }
    
    async update(id: number, updateSysDictDto: UpdateSysDictDto) {
        console.log('updateSysDictDto', updateSysDictDto);
        return ResultData.ok(await this.dictRepo.update(id, updateSysDictDto));
    }
    
    remove(id: number) {
        return `This action removes a #${id} sysDict`;
    }
}
